package com.ficus.road.maintain.config;

import cn.hutool.core.collection.CollectionUtil;
import com.ficus.road.maintain.service.DataProcessorManager;
import com.ficus.road.maintain.service.VideoService;
import com.ficus.road.maintain.websocket.BaseWebSocketManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {

    /**
     * 使用spring boot时，使用的是spring-boot的内置容器，
     * 如果要使用WebSocket，需要注入ServerEndpointExporter
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Autowired
    public void setDataProcessorManager(DataProcessorManager dataProcessorManager, VideoService videoService) {
        BaseWebSocketManager.dataProcessorManager = dataProcessorManager;
        BaseWebSocketManager.videoService = videoService;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        Map<String, Object> userProperties = sec.getUserProperties();
        Map<String, List<String>> headers = request.getHeaders();
        List<String> userAgent = headers.get("User-Agent");
        if(!CollectionUtil.isEmpty(userAgent)){
            userProperties.put("User-Agent", userAgent);
        }
    }
}